
// import { uniRequest,run } from './syncRequest'

// function loadConfigFile(path){
// 	debugger
// 	function requestJson(path){
// 		const data = uniRequest(path)
// 	}
// 	const aa = run(requestJson(path))
// }

import config from './config'

let configObj = {}
function initConfig(){
    // configObj = loadConfigFile('static/config/index.json')
	configObj = config
	configObj.replacehUrl = replacehUrl
	
	configObj.isTechnological = config.theme === 'technological'
	configObj.isCartoon = config.theme === 'cartoon'

	let en = window?.navigator?.userAgent?.toLowerCase()
	// 是否是微信浏览器
	configObj.isWxBrowser = en?.match(/MicroMessenger/i) == 'micromessenger'

	const type = uni.getSystemInfoSync().uniPlatform
	configObj.isVxProgram = 'mp-weixin' === type
	configObj.isH5 = 'web' === type

	console.log('配置文件：', configObj)
    return configObj
}

function replaceStringWithUrl(path, searchString, targetUrl) {
  const regex = new RegExp(`^${searchString}`);
  return targetUrl + path.replace(regex, '');
}

function parseQueryString(queryString) {
    const params = {};
    if (queryString) {
        const pairs = queryString.split('&');
        for (let i = 0; i < pairs.length; i++) {
            const pair = pairs[i].split('=');
            const key = decodeURIComponent(pair[0]);
            const value = decodeURIComponent(pair[1] || '');
            params[key] = value;
        }
    }
    return params;
}

function buildQueryString(params) {
    return Object.keys(params)
        .map(key => encodeURIComponent(key) + '=' + encodeURIComponent(params[key]))
        .join('&');
}

function replacehUrl(url,isToken = false){
    let newUrl = url
    Object.keys(configObj.serverUrls).some(key => {
        newUrl = replaceStringWithUrl(url, key,configObj.serverUrls[key] )
        return true;
    });
	const token = uni.getStorageSync("token");
	if (isToken || token) {
		const urlParts = newUrl.split('?');
		let basePath = urlParts[0];
		let queryString = urlParts[1] || '';
		let params = parseQueryString(queryString);
 
		if (!params.token) {
			params.token = token || '';
		}
 
		newUrl = basePath + '?' + buildQueryString(params);
	}
 
	return newUrl;
}

initConfig()
export default {
    ...configObj,
    replacehUrl
}
